package com.zenchn.utils;

import com.zenchn.model.TSysAuthority;
import com.zenchn.entity.AuthTreeVO;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * 权限数据通用操作类
 *
 * @author dingxinfa
 * @date 2020-04-24
 **/
public class AuthUtils {


    /**
     * 使用递归方法建树
     * @param authList  所有权限列表
     * @return
     */
    public static List<AuthTreeVO> treeBuilder(List<TSysAuthority> authList) {
        List<AuthTreeVO> authTreeVOList = new ArrayList<AuthTreeVO>();
        if (null!=authList && !authList.isEmpty()) {
            for (TSysAuthority authority : authList) {
                if (authority.getAuthLevel() == 1) {
                    AuthTreeVO authTreeVO = setAuthTreeVO(authority);
                    authTreeVOList.add(findChildren(authTreeVO, authList));
                }
            }
        }
        return authTreeVOList;
    }

    /**
     * 递归查找子节点
     * @param parentAuthTreeVO  父级节点信息
     * @param authList    建树所有权限列表
     * @return
     */
    private static AuthTreeVO findChildren(AuthTreeVO parentAuthTreeVO,List<TSysAuthority> authList) {
        ListIterator<TSysAuthority> iterator = authList.listIterator();

        while (iterator.hasNext()) {
            TSysAuthority authority= iterator.next();
            if(parentAuthTreeVO.getAuthId().equals(authority.getParentId())) {
                AuthTreeVO authTreeVO=setAuthTreeVO(authority);
                if (parentAuthTreeVO.getChildren() == null) {
                    parentAuthTreeVO.setChildren(new ArrayList<AuthTreeVO>());
                }
                parentAuthTreeVO.getChildren().add(findChildren(authTreeVO,authList));
            }

        }

        if (null!=parentAuthTreeVO.getChildren() && !parentAuthTreeVO.getChildren().isEmpty()){
            parentAuthTreeVO.setLeaf(false);
        }else{
            parentAuthTreeVO.setLeaf(true);
            parentAuthTreeVO.setChildren(null);
        }

        return parentAuthTreeVO;
    }


    /***
     * 组装建立 AuthTreeVO
     * @param authority
     * @return
     */
    public static  AuthTreeVO setAuthTreeVO(TSysAuthority authority){
        AuthTreeVO authTreeVO=new AuthTreeVO();
        authTreeVO.setAuthId(authority.getAuthId());
        authTreeVO.setAuthLevel(authority.getAuthLevel());
        authTreeVO.setAuthName(authority.getAuthName());
        authTreeVO.setParentId(authority.getParentId());


        return authTreeVO;
    }



}
